package org.janon.httpproxy.client.method;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.net.Socket;
import java.util.List;

import org.janon.httpproxy.HttpModel;
import org.janon.httpproxy.HttpUtil;

public class SendConnectData
{
	public static void send(String serverHost, int serverPort, String key,
			HttpModel httpModel, byte[] data, int off, int len, ConnectReadMethod crm)
			throws Exception
	{
		Socket sendSocket = null;
		BufferedOutputStream server_out = null;
		BufferedInputStream server_in = null;
		boolean flag = false;
		while(!flag)
		{
			if(sendSocket!=null)
			{
				try
				{
					sendSocket.close();
				}catch(Exception ex){}
			}
			sendSocket = new Socket(serverHost, serverPort);
			server_out = new BufferedOutputStream(sendSocket
					.getOutputStream());
			server_in = new BufferedInputStream(sendSocket
					.getInputStream());
	
			server_out.write(("GET / HTTP/1.1" + HttpUtil.CRLF).getBytes());
			server_out.write(("Connect-Header: "
					+ org.janon.util.Base64.Encode(HttpUtil.HTTP_CONNECT_CONTINUE
							+ key + "1") + HttpUtil.CRLF).getBytes());
			List<String> requestHeader = httpModel.getRequestHeader();
	
			for (int i = 0, len1 = requestHeader.size(); i < len1; i++)
			{
				if (!HttpUtil.startsWith(requestHeader.get(i), "Content-Length: "))
				{
					server_out.write((requestHeader.get(i) + HttpUtil.CRLF).getBytes());
					server_out.flush();
				}
			}
			if (len > -1)
			{
				server_out.write(("Content-Length: " + len + HttpUtil.CRLF).getBytes());
				server_out.write((HttpUtil.CRLF).getBytes());
				server_out.write(data, off, len);
			}
			else if(len==-2)
			{
				server_out.write(("Cookie: ACTIONID=" + org.janon.util.Base64.Encode("REFRESH") + HttpUtil.CRLF).getBytes());
				server_out.write((HttpUtil.CRLF).getBytes());
			}
			else
			{
				server_out.write((HttpUtil.CRLF).getBytes());
			}
			server_out.flush();
	
			String temp;
			flag = false;
			while (true)
			{
				temp = HttpUtil.readLine(server_in);
	
				if (temp == null || temp.length() == 0)
				{
					break;
				}
				else if(HttpUtil.startsWith(temp, "Set-Cookies: "))
				{
					if(temp.indexOf(key)!=-1)
					{
						flag = true;
					}
				}
			}
		}
		if(len!=-1)
		{
			crm.setServerInputStream(server_in, sendSocket);
		}
		else
		{
			crm.removeServerInputStreams();
		}
//		sendSocket.close();
	}
}
